<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;

class CreateDatabase implements ShouldQueue
{

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle($event)
    {
        // 创建数据库
        $this->createDatabase();
    }

    // 创建数据库
    private function createDatabase()
    {
        // 设置运行永远不会超时
        $DB_HOST = env('DB_HOST');
        $DB_DATABASE = env('DB_DATABASE'); //从配置文件中获取数据库信息
        $DB_USERNAME = env('DB_USERNAME');
        $DB_PASSWORD = env('DB_PASSWORD');

        $dns = "mysql:host={$DB_HOST};charset=utf8";
        // 连接数据库
        $link = new \PDO($dns, $DB_USERNAME, $DB_PASSWORD);// 连接数据库
        $link->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        // 创建数据库
        $sql = "CREATE DATABASE IF NOT EXISTS {$DB_DATABASE} DEFAULT CHARSET utf8mb4 -- UTF-8 Unicode COLLATE utf8mb4_unicode_ci";
        $link->exec($sql);
        $link = null;
    }
}
